# encoding: utf-8

class PushHistory
  include Mongoid::Document
  include Mongoid::Timestamps

  field :comment, :type => String
  field :tweets_list, :type => Array, :default => {}
  # belongs_to :weibo_user, :class => Statistics::WeiboUser
  belongs_to :task
  has_many :tweets, :class_name => 'Statistics::Tweet'


  def add_tweet(result, for_t)
    search_type = task.search_type.downcase
    result['for_t'] = for_t
    if result['error_code'].present? || result["errcode"].to_i != 0 || result['error'].present?
      # result = result['wid']
      # TODO 想办法获取完整的tweet

      if _page = Utility::Page.where(:page_token => "#{task._id}_#{task.search_type.downcase}_p#{for_t['pindex']}").first
        logger.info ">评论出错: 从Page缓存中获取完整的Tweet"
        result['status'] = _page.tweets[for_t['index'].to_i]
        _page.tweets[for_t['index'].to_i]['commented'] = "发送失败-#{ result["error"] || result["msg"] || result['error_code'] }"
        _page.save
        self.send("assign_#{search_type}", result)
      else
        @tweet.destroy
      end
    else
      self.send("assign_#{search_type}", result)
      if _page = Utility::Page.where(:page_token => "#{task._id}_#{task.search_type.downcase}_p#{for_t['pindex']}").first
        p ">发送成功:修改原始Page数据"
        _page.tweets[for_t['index'].to_i]['commented'] = "发送成功"
        _page.save
      end
    end
  end

  def assign_weibo(result)
    _sns_user = result['status']['user']
    weibo     = result['status']
    sns_user  = Statistics::SnsUser.find_or_create_by(:uid => _sns_user['id'])
    sns_user.update_attributes(
      :name              => _sns_user['name'],
      :province          => _sns_user['province'],
      :city              => _sns_user['city'],
      :location          => _sns_user['location'],
      :gender            => _sns_user['gender'] == 'm' ? '男' : (_sns_user['gender'] == 'f' ? '女' : '未知'),
      :followers_count   => _sns_user['followers_count'],
      :profile_image_url => _sns_user['profile_image_url'],
      :screen_name       => _sns_user['screen_name'],
      :type              => :weibo
      )
    @tweet.update_attributes(
      :text             => weibo['text'],
      :comments_count   => weibo['comments_count'],
      :created_at       => Time.parse(weibo['created_at']).to_i,
      :location         => _sns_user['location'],
      :sns_type         => 'Weibo',
      :error            => result["error"] || result['error_code'] ||  result["errcode"] ,
      :sns_user         => sns_user,
      :for_t            => result['for_t']
      )
    if _sns_user
      _mid = Utility.get_j("http://api.t.sina.com.cn/querymid.json?id=#{weibo["id"]}&type=1")["mid"]
      result["wurl"] = "http://weibo.com/#{weibo["user"]["id"]}/#{_mid}" if _mid.present?
      logger.info ">结果记录: 设置微博地址#{result["wurl"]}"
      @tweet.update_attributes(
        :wurl             => result["wurl"]
      )
    end
    if result["user"]

      @tweet.update_attributes(
        :cid              => result["id"],
        :cuser            => result["user"],
        :spammer_id       => result["user"]["id"],
      )

    end
  end

  def assign_tencent(result)
    search_type = task.search_type.downcase
    for_t = result['for_t']
    if _page = Utility::Page.where(:page_token => "#{task._id}_tencent_p#{for_t['pindex']}").first
      tweet  = _page.tweets[for_t['index'].to_i]
      _sns_user = tweet['user']
    else
      p ">保存记录: 找不到page"
      return false
    end


    sns_user  = Statistics::SnsUser.find_or_create_by(:uid => _sns_user['id'])
    sns_user.update_attributes(
      :name              => _sns_user['name'],
      :province          => _sns_user['province'],
      :city              => _sns_user['city'],
      :location          => _sns_user['location'],
      :gender            => _sns_user['gender'] == 'm' ? '男' : (_sns_user['gender'] == 'f' ? '女' : '未知'),
      :followers_count   => _sns_user['followers_count'],
      :profile_image_url => _sns_user['profile_image_url'],
      :screen_name       => _sns_user['screen_name'],
      :recent_sent       => Time.now,
      :type              => :tencent
      )
    @tweet.update_attributes(
      :text             => tweet['text'],
      :comments_count   => tweet['comments_count'],
      :created_at       => tweet['created_at'].to_i,
      :location         => _sns_user['location'],
      :sns_type         => 'Weibo',
      :error            => result["errcode"] == 0 ? nil : result["msg"] ,
      :sns_user         => sns_user,
      :for_t            => for_t
      )
    if _sns_user
      result["wurl"] = "http://t.qq.com/p/t/#{tweet["id"]}"
      logger.info ">结果记录: 设置微博地址#{result["wurl"]}"
      @tweet.update_attributes(
        :wurl             => result["wurl"]
      )
    end
    if result["user"]

      @tweet.update_attributes(
        :cid              => result["id"],
        :cuser            => result["user"],
        :spammer_id       => result["user"]["id"],
      )

    end
  end

  def sign_commented

  end

  def new_tweet(wid)
    @tweet = self.tweets.find_or_create_by(:wid => wid)
  end

  def new_user_record

  end

end